import { fetchNewTokenByRefreshToken as apiRefreshToken } from "@/api/login";

// 检查 Token 是否过期（提前30秒过期，避免网络延迟）
export const checkTokenExpirationStatus = (tokenType = "access") => {
  try {
    let expiryTime;

    if (tokenType === "access") {
      expiryTime = localStorage.getItem("accessExpiryTime");
    } else if (tokenType === "refresh") {
      expiryTime = localStorage.getItem("refreshExpiryTime");
    } else {
      return true;
    }

    // 检查是否存在过期时间
    if (!expiryTime) {
      return true;
    }

    // 将字符串转换为数字，然后创建Date对象
    const expiryTimestamp = parseInt(expiryTime, 10);

    // 验证是否是有效的时间戳
    if (isNaN(expiryTimestamp) || expiryTimestamp <= 0) {
      return true;
    }

    // 提前30秒判断为过期，避免网络延迟
    const bufferTime = 30 * 1000; // 30秒缓冲时间
    return Date.now() >= expiryTimestamp - bufferTime;
  } catch (error) {
    console.error("检查token过期时间时出错:", error);
    return true;
  }
};

// 保存 Token 到 localStorage
export const saveTokenInfo = (tokenData) => {
  // 检查必要字段
  if (!tokenData.accessToken || !tokenData.refreshToken) {
    throw new Error("Token数据不完整");
  }

  localStorage.setItem("accessToken", tokenData.accessToken);
  localStorage.setItem("refreshToken", tokenData.refreshToken);

  // 处理过期时间
  let accessExpiryTime = tokenData.accessExpiresIn;
  let refreshExpiryTime;

  const existingRefreshExpiry = localStorage.getItem("refreshExpiryTime");
  if (tokenData.refreshExpiresIn) {
    // 如果后端返回了refreshExpiresIn，使用新的
    refreshExpiryTime = tokenData.refreshExpiresIn;
  } else if (existingRefreshExpiry) {
    // 使用原有的refreshExpiresIn
    refreshExpiryTime = existingRefreshExpiry;
  }

  // 以字符串形式存储
  localStorage.setItem("accessExpiryTime", accessExpiryTime.toString());
  localStorage.setItem("refreshExpiryTime", refreshExpiryTime.toString());
};

// 清除 localStorage 中的 Token 信息
export const clearTokenInfo = () => {
  localStorage.removeItem("accessToken");
  localStorage.removeItem("refreshToken");
  localStorage.removeItem("openIdWeb");
  localStorage.removeItem("accessExpiresIn");
  localStorage.removeItem("refreshExpiresIn");
  localStorage.removeItem("accessExpiryTime");
  localStorage.removeItem("refreshExpiryTime");
};

// 刷新 AccessToken
export const refreshAndGetNewAccessToken = async () => {
  try {
    const response = await apiRefreshToken();

    // 检查响应结构
    if (!response) {
      throw new Error("无效的API响应");
    }

    if (response.code === 0 && response.data) {
      // 保存新的Token信息
      saveTokenInfo(response.data);

      return response.data.accessToken;
    } else {
      throw new Error(response.message || "Token刷新失败");
    }
  } catch (error) {
    console.error("刷新Token失败:", error);
    clearTokenInfo();
    throw error;
  }
};

// 创建带 Token 的请求头
export const createAuthHeader = (contentType = "application/json") => {
  const header = {
    "Content-Type": contentType,
  };

  const accessToken = localStorage.getItem("accessToken");
  if (accessToken) {
    // 直接使用当前Token，刷新逻辑在拦截器中统一处理
    header["Authentication"] = `Bearer ${accessToken}`;
  }
  return header;
};
